/*
Author: Pratibh Prakash
Company: Fujitsu America
Created Date: 17 Sep-2009
Description: Trigger populates Original Lead Owner field on Lead if Owner of lead is a user 
             and once this field populated by user value then it never allows value to be changed. 
             
ModifiedBy: Andrey Volosevich 
Modified Date: 11 Nov-2009
Change Description: Added additional logic on Insert action that will check the running user Id and will NOT populate 
					Original Lead Owner field is runing user ID is listed in the IM_Original_Lead_Owner_Exceptions cusotm label.
					This is to prevent system account (i.e. Eloqua/DemandTools) from being populated in the OLO field.
					
*/

trigger PopulateOriginalLeadOwner on Lead (before insert, before update) {
    
    String ownerIdval;
    String runningUserId = UserInfo.getUserId().substring(0,15);
    String exceptionUserIds = Label.IM_Original_Lead_Owner_Exceptions;
    
    System.debug('********* Running UserId: ' + runningUserId);
    System.debug('********* Exception User Ids String: ' + exceptionUserIds);
    
    if(Trigger.isBefore && Trigger.isInsert){
        System.debug('******Before Insert**********');
        for(Integer i=0; i<Trigger.new.size(); i++){
            ownerIdval = Trigger.new[i].OwnerId;
            
            //If OwnerId is not a Queue and not listed as Exception user then assigning value to Original Lead Owner field.
            if(!ownerIdval.startsWith('00G') && !exceptionUserIds.contains(runningUserId)){
            	
                System.debug('*****User in OwnerId*****');
                Trigger.new[i].IM_Original_Lead_Owner__c = Trigger.new[i].OwnerId;
            }
        }
    }
    if(Trigger.Isbefore && Trigger.isUpdate){
        System.debug('*******In Before Update*****');
        //Map<Id, Lead> leadMapOld = new Map<Id, Lead>();
        //leadMapOld.putAll(Trigger.oldMap);
        for(Integer i=0; i<Trigger.new.size(); i++){
            ownerIdval = Trigger.new[i].OwnerId;

            //If OwnerId is not a Queue then assigning value to Original Lead Owner field.
            if( Trigger.oldMap.get(Trigger.new[i].Id).IM_Original_Lead_Owner__c == null && !ownerIdval.startsWith('00G')){
                System.debug('*****User in OwnerId*****');
                Trigger.new[i].IM_Original_Lead_Owner__c = Trigger.new[i].OwnerId;
            }
        }
    }
}